package io.agilefast.modules.customer.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.agilefast.basic.base.BaseController;
import io.agilefast.basic.service.SysDictService;
import io.agilefast.common.api.R;
import io.agilefast.common.api.R2;
import io.agilefast.common.api.Result;
import io.agilefast.common.utils.*;
import io.agilefast.common.vo.MinioUploadVo;
import io.agilefast.modules.customer.entity.CustomerIndustryEntity;
import io.agilefast.modules.customer.form.CustomerIndustryParams;
import io.agilefast.modules.customer.form.ImPortProductParams;
import io.agilefast.modules.customer.service.CustomerIndustryService;

import io.agilefast.modules.plm.entity.PlmProductEntity;

import io.agilefast.modules.plm.form.ProductParams;
import io.minio.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController("CustomerIndustryController")
@RequestMapping("/api/plm/customer")
@Tag(name = "顾客管理")
public class CustomerIndustryController extends BaseController {

    @Autowired
    private CustomerIndustryService customerIndustryService;



    @PostMapping("/getCustomerByPage")
    @Operation(summary = "获取顾客列表")
    public Result<List<CustomerIndustryEntity>> getIndustryByPage(@RequestBody CustomerIndustryParams form) {
        // 调用服务层的分页查询方法
        PageUtils customerPages = customerIndustryService.queryPage(form);

//        // 获取分页数据
//        List<CustomerIndustryEntity> list = (List<CustomerIndustryEntity>) customerPages.getList();
//
//        // 包装成 CommonPage 对象返回
//        CommonPage<List<CustomerIndustryEntity>> listCommonPage = new CommonPage<List<CustomerIndustryEntity>>()
//                .setData(list, customerPages.getTotalCount());

        // 返回顾客分页数据
        List<CustomerIndustryEntity> resultList =  (List<CustomerIndustryEntity>)customerPages.getList();
        for (CustomerIndustryEntity item : resultList) {
            if (StringUtils.isNotBlank(item.getProfilePicture())) {
                item.setProfilePicture("http://localhost:8082" + item.getProfilePicture());
            }
        }
        return R2.ok(resultList);
    }


    @PostMapping("/saveCustomer")
    @Operation(summary ="保存顾客")
    public Result<R> saveIndustry(@RequestBody CustomerIndustryEntity customerEntity) {
        return customerIndustryService.save(customerEntity) ? R2.setOkMsg("保存顾客行业成功") :  R2.setErrMsg("保存顾客行业失败");
    }

    @PostMapping("/updateCustomer")
    @Operation(summary ="修改顾客")
    public Result<R> updateIndustry(@RequestBody CustomerIndustryEntity customerEntity) {
        return customerIndustryService.updateById(customerEntity) ? R2.setOkMsg("修改产品行业成功") : R2.setErrMsg("修改产品行业失败");
    }

    @PostMapping("/deleteCustomer")
    @Operation(summary ="删除顾客")
    public Result<R> deleteIndustry(@RequestBody Long[] params) {
        // 检查参数是否为空
        if (params == null || params.length == 0) {
            return R2.setErrMsg("删除顾客失败，参数不能为空！");
        }

        boolean re;
        if (params.length == 1) {
            // 删除单个顾客
            re = customerIndustryService.removeById(params[0]);
        } else {
            // 删除多个顾客
            re = customerIndustryService.remove(new QueryWrapper<CustomerIndustryEntity>().in("customer_id", params));
        }

        // 返回删除操作的结果
        return re ? R2.setOkMsg("删除顾客成功") : R2.setErrMsg("删除顾客失败");
    }


    @Value("${web.config.webFileUrl}")
    private String webFileUrl;
    @Value("${web.config.filePrefix}")
    private String filePrefix;

    @Operation(summary = "文件上传")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Result<String> upload(MultipartFile file, HttpServletRequest request) {
        String subPath = "\\upload\\headImg\\";
        String basepath = webFileUrl;
        String path = "";
        String vpath = "";
        String fileType = "";
        List<String> vpathList = new ArrayList<>();
        Map<String, Object> resultPath = WebFileUtils.saveFile(file, basepath + subPath, request);
        path = resultPath.get("path").toString();
        fileType = resultPath.get("fileType").toString();
        vpath = filePrefix + "/upload/" + "headImg" + "/" + fileType + "/" + new File(path).getName();
        return R2.ok(vpath);
    }

    @PostMapping("/exportList")
    @Operation(summary = "导出")
    public void export(@RequestBody CustomerIndustryParams form, HttpServletResponse response) throws IOException {


        List<CustomerIndustryEntity> list = customerIndustryService.list();
        List<ExportVO> exportVOList = BeanUtil.copyToList(list, ExportVO.class);
        ExcelUtils.write(response, "顾客信息列表.xlsx", "数据列表", ExportVO.class, exportVOList);
    }

    @PostMapping("/importProductExcel")
    @Operation(summary = "批量导入列表")
//    @ApiOperation("批量导入列表")
    public R importProductExcel(@RequestBody List<Map<String, Object>> crmProductVos) throws Exception {

        long stime = System.currentTimeMillis();
        List<ImPortProductParams> productList = new ArrayList<>();
        List<CustomerIndustryEntity> products = new ArrayList<>();
        Class clazz = new ImPortProductParams().getClass();
        for (Map<String, Object> product : crmProductVos) {
            Object entity = ExcelUtils.getExcelEntity(clazz, product);
            productList.add((ImPortProductParams) entity);
        }

        for (ImPortProductParams item : productList) {
            CustomerIndustryEntity customerIndustryEntity = new CustomerIndustryEntity();
            customerIndustryEntity.setCustomerName(item.getCustomerName());
            customerIndustryEntity.setGender(item.getGender());
            customerIndustryEntity.setCustomerStatus(item.getCustomerStatus());
//            CustomerIndustryEntity.setProductId(GeneratId.getGeneratID());
            products.add(customerIndustryEntity);
        }
        boolean re = customerIndustryService.insertBatchs(products);
        long etime = System.currentTimeMillis();
        System.out.printf("执行时长：%d 毫秒.", (etime - stime));
        return re ? R.ok() : R.error();

    }


}



